<template>
  <view class="container">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar">
      <view class="navbar-title">{{ t('prescription.title') }}</view>
    </view>

    <!-- 临床诊断区 -->
    <view class="clinical-diagnosis-section">
      <view class="section-header">
        <text class="section-icon">✏️</text>
        <text class="section-title">{{ t('prescription.clinical_diagnosis') }}</text>
        <text class="section-subtitle">({{ t('prescription.diagnosis') }}、{{ t('prescription.syndrome_differentiation') }}至少填写一项)</text>
      </view>
      
      <view class="diagnosis-content">
                 <!-- 诊断 -->
         <view class="diagnosis-row">
           <text class="diagnosis-label">{{ t('prescription.diagnosis') }}</text>
           <view class="diagnosis-input-area">
             <view v-if="selectedDiagnoses.length === 0" class="diagnosis-input-container">
               <button class="add-diagnosis-btn" @click="openDiagnosisModal">
                 <text class="add-icon">+</text>
                 <text class="add-text">{{ t('prescription.add_diagnosis') }}</text>
               </button>
             </view>
             <view v-else class="diagnosis-display">
               <view class="diagnosis-list">
                 <view v-for="(diagnosis, index) in selectedDiagnoses" :key="diagnosis.id" class="diagnosis-item">
                   <text class="diagnosis-text">{{ diagnosis.fjbname }}</text>
                   <button class="remove-diagnosis-btn" @click="removeDiagnosis(index)">×</button>
                 </view>
               </view>
               <view class="edit-diagnosis-container">
                 <button class="edit-diagnosis-btn" @click="openDiagnosisModal">+{{ t('prescription.add_diagnosis') }}</button>
               </view>
             </view>
           </view>
         </view>
        
        <!-- 辨证 -->
        <view class="diagnosis-row">
          <text class="diagnosis-label">{{ t('prescription.syndrome_differentiation') }}</text>
          <view class="diagnosis-input-area">
            <input 
              v-model="formData.dialectic" 
              class="syndrome-input" 
              :placeholder="t('prescription.syndrome_placeholder')"
            />
          </view>
        </view>
      </view>
    </view>

    <!-- 中药选择区 -->
    <view class="medicine-selection-section">
      <view class="section-header">
        <text class="section-title">🌿 {{ t('prescription.select_medicine') }}</text>
      </view>
      
      <button class="fill-helper-btn medicine-btn" @click="gotoMedicineSelect">
        {{ t('prescription.select_medicine') }}
      </button>
      
      <!-- 已选中药列表 -->
      <view v-if="selectedMedicines.length > 0" class="selected-medicines-list">
        <view v-for="(medicine, index) in selectedMedicines" :key="medicine.id" class="selected-medicine-item">
          <view class="medicine-info-group">
            <view class="medicine-info">
              <view class="medicine-title">{{ medicine.drugs_name }}</view>
              <view class="medicine-meta">
                <text class="medicine-quantity">{{ t('prescription.quantity') }}: {{ medicine.quantity }}g</text>
                <text class="medicine-method">{{ t('prescription.decoction') }}: {{ medicine.decoction_method }}</text>
              </view>
            </view>
          </view>
          <button class="remove-medicine-btn" @click="removeMedicine(index)">{{ t('prescription.remove_product') }}</button>
        </view>
        
        <!-- 药量计算器 -->
        <view class="dosage-calculator">
          <view class="calculator-header">
            <text class="calculator-icon">🧮</text>
            <text class="calculator-title">{{ t('prescription.dosage_calculator') }}</text>
          </view>
          <view class="calculator-content">
            <view class="dosage-info">
              <text class="dosage-text">{{ totalMedicineWeight }}{{ t('prescription.total_per_dose') }}</text>
              <text class="dosage-label">{{ t('prescription.total_doses') }}</text>
              <view class="quantity-selector">
                <button class="quantity-btn minus" @click="decreaseDosage" :disabled="dosageCount <= 1">-</button>
                <input 
                  v-model="dosageCount" 
                  class="quantity-input" 
                  type="number" 
                  min="1" 
                  @input="onDosageCountChange"
                />
                <button class="quantity-btn plus" @click="increaseDosage">+</button>
              </view>
              <text class="dosage-label">{{ t('prescription.dose') }}</text>
              <text class="total-dosage">{{ t('prescription.total_weight') }}{{ totalDosageWeight }}g</text>
            </view>
          </view>
        </view>
        
        <!-- 用法用量 -->
        <view class="usage-dosage-section">
          <view class="section-header">
            <text class="section-icon">💊</text>
            <text class="calculator-title">{{ t('prescription.usage_dosage') }}</text>
          </view>
          <view class="usage-content">
            <view class="usage-row">
              <text class="required-mark">*</text>
              <input 
                v-model="formData.usage_days" 
                class="usage-input" 
                type="number" 
                min="1" 
                placeholder="1"
              />
              <text class="usage-unit">{{ t('prescription.days') }}</text>
              <input 
                v-model="formData.usage_doses" 
                class="usage-input" 
                type="number" 
                min="1" 
                placeholder="1"
              />
              <text class="usage-unit">{{ t('prescription.doses_per_day') }}</text>
              <text class="required-mark">*</text>
              <text class="usage-text">{{ t('prescription.times_per_dose') }}</text>
              <input 
                v-model="formData.usage_times" 
                class="usage-input" 
                type="number" 
                min="1" 
                placeholder="2"
              />
              <text class="usage-text">{{ t('prescription.times') }}</text>
              <text class="required-mark">*</text>
              <text class="usage-text">{{ t('prescription.amount_per_time') }}</text>
              <input 
                v-model="formData.usage_amount" 
                class="usage-input amount-input" 
                type="number" 
                min="1" 
                placeholder="150"
              />
              <text class="usage-unit">{{ t('prescription.ml') }}</text>
            </view>
            
            <!-- 备注信息 -->
            <view class="remarks-content">
              <view class="remarks-header">
                <text class="remarks-icon">📝</text>
                <text class="remarks-title">{{ t('prescription.remarks_title') }}</text>
              </view>
              <view class="remarks-input-area">
                <text v-if="!formData.usage_notes" class="remarks-placeholder" @click="showRemarksInput">{{ t('prescription.remarks_placeholder') }}</text>
                <view v-else class="remarks-display">
                  <text class="remarks-text">{{ formData.usage_notes }}</text>
                  <button class="edit-remarks-btn" @click="showRemarksInput">{{ t('prescription.edit') }}</button>
                </view>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 用药医嘱 -->
        <view class="medication-instructions-section">
          <view class="section-header">
            <text class="section-icon">💊</text>
            <text class="calculator-title">{{ t('prescription.medication_instructions') }}</text>
          </view>
          <view class="medication-content">
            <!-- 用药说明 -->
            <view class="medication-row">
              <text class="medication-label required-mark">*</text>
              <text class="medication-text">{{ t('prescription.medication_description') }}</text>
              <view class="medication-input-area" @click="showMedicationInstructionsInput">
                <text v-if="!formData.medication_instructions" class="medication-placeholder">{{ t('prescription.please_input') }}</text>
                <view v-else class="medication-display">
                  <text class="medication-value">{{ formData.medication_instructions }}</text>
                  <button class="edit-medication-btn" @click.stop="showMedicationInstructionsInput">{{ t('prescription.edit') }}</button>
                </view>
              </view>
              <text class="medication-arrow">></text>
            </view>
            
            <!-- 用药时间 -->
            <view class="medication-row">
              <text class="medication-label required-mark">*</text>
              <text class="medication-text">{{ t('prescription.medication_time') }}</text>
              <view class="medication-input-area" @click="showMedicationTimePicker">
                <text v-if="!formData.medication_time" class="medication-placeholder">{{ t('prescription.please_select') }}</text>
                <view v-else class="medication-display">
                  <text class="medication-value">{{ formData.medication_time }}</text>
                  <button class="edit-medication-btn" @click.stop="showMedicationTimePicker">{{ t('prescription.edit') }}</button>
                </view>
              </view>
              <text class="medication-arrow">></text>
            </view>
            
            <!-- 用药禁忌 -->
            <view class="medication-row">
              <text class="medication-label"></text>
              <text class="medication-text">{{ t('prescription.medication_contraindications') }}</text>
              <view class="medication-input-area" @click="showMedicationContraindicationsPicker">
                <text v-if="!formData.medication_contraindications" class="medication-placeholder">{{ t('prescription.please_select') }}</text>
                <view v-else class="medication-display">
                  <text class="medication-value">{{ formData.medication_contraindications }}</text>
                  <button class="edit-medication-btn" @click.stop="showMedicationContraindicationsPicker">{{ t('prescription.edit') }}</button>
                </view>
              </view>
              <text class="medication-arrow">></text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 理疗师信息 -->
    <view class="therapist-info-section">
      <view class="section-header">
        <text class="section-icon">👨‍⚕️</text>
        <text class="section-title">{{ t('medical.therapist_info') }}</text>
      </view>
      
      <view class="therapist-content">
        <!-- 治疗师姓名 -->
        <view class="therapist-row">
          <text class="therapist-label">{{ t('medical.therapist_name') }}</text>
          <view class="therapist-value">{{ getTherapistName() }}</view>
        </view>
        
        <!-- 治疗师签名 -->
        <view class="therapist-row">
          <text class="therapist-label">{{ t('medical.therapist_signature') }}</text>
          <view class="therapist-signature-display">
            <image 
              v-if="therapistSignature" 
              :src="therapistSignature" 
              class="therapist-signature-image" 
              mode="aspectFit"
            />
            <text v-else class="no-signature">{{ t('medical.no_signature') }}</text>
          </view>
          <button class="therapist-sign-btn" @click="gotoTherapistSign">{{ t('medical.re_sign') }}</button>
        </view>
        
        <!-- 治疗师日期 -->
        <view class="therapist-row">
          <text class="therapist-label">{{ t('medical.therapist_date') }}</text>
          <view class="therapist-value">{{ getCurrentDate() }}</view>
        </view>
      </view>
    </view>

    <!-- 固定底部提交按钮 -->
    <view class="fixed-bottom-btn">
      <button class="fill-btn" @click="submitPrescription">{{ t('prescription.submit_prescription') }}</button>
    </view>
    
         <!-- 诊断选择弹窗 -->
     <view v-if="showDiagnosisModal" class="diagnosis-modal-overlay" @click="closeDiagnosisModal">
       <view class="diagnosis-modal" @click.stop>
         <view class="modal-header">
           <text class="modal-title">{{ t('prescription.add_diagnosis') }}</text>
           <button class="close-btn" @click="closeDiagnosisModal">×</button>
         </view>
         
         <view class="modal-search">
           <input 
             v-model="diagnosisSearch" 
             class="modal-search-input" 
             :placeholder="t('prescription.diagnosis_search_placeholder')"
             @input="onDiagnosisSearch"
             @focus="showDiagnosisSearchResults = true"
           />
           <button v-if="diagnosisSearch.trim()" class="clear-search-btn" @click="clearDiagnosisSearch">×</button>
         </view>
         
            <view class="modal-results" ref="modalResults" @scroll="onModalScroll" @touchmove="onModalTouchMove">
             
             <view v-if="diagnosisLoading" class="search-loading">
               {{ t('common.loading') }}
             </view>
             <view v-else-if="diagnosisSearchResults.length === 0 && diagnosisSearch.trim()" class="search-no-results">
               {{ t('prescription.no_diagnosis_results') }}
             </view>
             <view v-else-if="diagnosisSearchResults.length > 0" class="search-result-list">
               <view 
                 v-for="item in diagnosisSearchResults" 
                 :key="item.id" 
                 class="search-result-item"
                 @click="selectSingleDiagnosis(item)"
               >
                 <view class="result-content">
                   <text class="result-name">{{ item.fjbname }}</text>
                   <text class="result-code" v-if="item.ficdversion">({{ item.ficdversion }})</text>
                 </view>
                 <view class="selection-indicator">
                   <text class="unselected-icon">○</text>
                 </view>
               </view>
               
               <!-- 加载中提示 -->
               <view v-if="isRefreshing" class="loading-more">
                 {{ t('prescription.loading_more') }}
               </view>
               
               <!-- 没有更多数据提示 -->
               <view v-if="!hasMoreData && diagnosisSearchResults.length > 0" class="no-more-data">
                 {{ t('prescription.no_more_data') }}
               </view>
               
               <!-- 下拉翻页提示 -->
               <view v-if="showPullToRefresh" class="pull-to-refresh">
                 {{ t('prescription.pull_to_refresh') }}
               </view>
             </view>
             <view v-else class="search-placeholder">
               {{ t('prescription.search_placeholder_text') }}
             </view>
           </view>
       </view>
     </view>
  </view>
</template>

<script>
import { useI18n } from 'vue-i18n'
import { useUserStore } from '@/store/user.js'
import { getDict, getDisease, treatmentRecordChineseMedicine } from '@/api/medical.js'
import { resetSignature } from '@/api/user.js'

export default {
  data() {
    return {
      selectedMedicines: [], // 选中的中药列表
      dosageCount: 1, // 剂数
      formData: {
        // 用法用量相关字段
        usage_days: 1, // 服用天数
        usage_doses: 1, // 每日剂数
        usage_times: 2, // 每剂分几次服用
        usage_amount: 150, // 每次服用量(ml)
        usage_notes: '', // 备注信息
        // 用药医嘱相关字段
        medication_instructions: '', // 用药说明
        medication_time: '', // 用药时间
        medication_contraindications: '', // 用药禁忌
        // 临床诊断相关字段
        diagnosis: '', // 诊断
        dialectic: '', // 辨证
      },
      // 用药医嘱相关数据
      medicationTimeOptions: [], // 用药时间选项
      medicationContraindicationsOptions: [], // 用药禁忌选项
      medicalRecordData: {}, // 从medical-details页面传递的医疗记录数据
      therapistSignature: '', // 治疗师签名图片URL
      
                     // 诊断和辨证相关数据
        diagnosisSearch: '', // 诊断搜索关键词
        diagnosisSearchResults: [], // 诊断搜索结果
        diagnosisLoading: false, // 诊断搜索加载状态
        showDiagnosisSearchResults: false, // 是否显示诊断搜索结果
        diagnosisSearchTimer: null, // 诊断搜索防抖定时器
        showDiagnosisModal: false, // 是否显示诊断弹窗
        selectedDiagnoses: [], // 已选择的诊断列表
                 // 分页相关
         isRefreshing: false, // 是否正在加载更多
         currentPage: 1, // 当前页码
         hasMoreData: true, // 是否还有更多数据
         showPullToRefresh: false, // 是否显示下拉翻页提示
         scrollThrottleTimer: null, // 滚动节流定时器
    }
  },
  
  setup() {
    const { t } = useI18n()
    const userStore = useUserStore()
    
    // 动态设置页面标题以支持国际化
    if (typeof uni !== 'undefined' && uni.setNavigationBarTitle) {
      uni.setNavigationBarTitle({
        title: t('prescription.title')
      })
    }
    return { t, userStore }
  },
  
  onReady() {
    // 进入页面时设置国际化标题
    if (typeof this.t === 'function') {
      uni.setNavigationBarTitle({
        title: this.t('prescription.title')
      })
    }
    
    // 获取用药医嘱相关数据
    this.loadMedicationData()
  },

  computed: {
    userStore() {
      return useUserStore()
    },
    userInfo() {
      return this.userStore.userInfo
    },
    
    // 计算所有中药的总重量（1剂）
    totalMedicineWeight() {
      return this.selectedMedicines.reduce((total, medicine) => {
        return total + (parseFloat(medicine.quantity) || 0);
      }, 0).toFixed(1);
    },
    
    // 计算总剂数重量
    totalDosageWeight() {
      const totalWeight = parseFloat(this.totalMedicineWeight) || 0;
      return (totalWeight * this.dosageCount).toFixed(1);
    }
  },

  onShow() {
    // 设置页面标题
    if (typeof this.t === 'function') {
      uni.setNavigationBarTitle({
        title: this.t('prescription.title')
      })
    }
    
    // 从本地存储获取医疗记录数据
    const medicalRecordData = uni.getStorageSync('medical_complete_record');
    if (medicalRecordData) {
      this.medicalRecordData = medicalRecordData;
    }
    
    // 添加点击外部区域隐藏搜索结果的功能
    this.addClickOutsideListener();
    
    // 加载治疗师签名
    this.loadTherapistSignature();
    
    // 监听中药选择事件
    uni.$once('medicineSelected', (medicines) => {
      // medicines 现在是一个数组，包含多个药品
      if (Array.isArray(medicines) && medicines.length > 0) {
        medicines.forEach(medicine => {
          // 检查中药是否已经选择过
          const existingIndex = this.selectedMedicines.findIndex(m => m.id === medicine.id);
          if (existingIndex === -1) {
            // 为中药添加必要字段
            const medicineWithDetails = {
              ...medicine,
              quantity: medicine.quantity || 0.5, // 数量
              decoction_method: medicine.decoction_method || this.t('drugs_select.decoction_methods.none') // 煎煮方法
            };
            
            // 添加新中药到中药列表
            this.selectedMedicines.push(medicineWithDetails);
          } else {
            // 如果中药已存在，更新其信息（包括煎煮方法）
            this.selectedMedicines[existingIndex] = {
              ...this.selectedMedicines[existingIndex],
              quantity: medicine.quantity || this.selectedMedicines[existingIndex].quantity,
              decoction_method: medicine.decoction_method || this.selectedMedicines[existingIndex].decoction_method
            };
          }
        });
      }
    });
    
    // 中药选择兜底
    const medicineKey = 'helper_selected_medicine';
    const localMedicine = uni.getStorageSync(medicineKey);
    if (localMedicine && Array.isArray(localMedicine)) {
      localMedicine.forEach(medicine => {
        // 检查中药是否已经选择过
        const existingIndex = this.selectedMedicines.findIndex(m => m.id === medicine.id);
        if (existingIndex === -1) {
          // 为中药添加必要字段
          const medicineWithDetails = {
            ...medicine,
            quantity: medicine.quantity || 0.5, // 数量
            decoction_method: medicine.decoction_method || this.t('drugs_select.decoction_methods.none') // 煎煮方法
          };
          
          // 添加新中药到中药列表
          this.selectedMedicines.push(medicineWithDetails);
        }
      });
      uni.removeStorageSync(medicineKey);
    }
  },

  onUnload() {
    // 页面销毁时清理定时器
    if (this.scrollThrottleTimer) {
      clearTimeout(this.scrollThrottleTimer);
      this.scrollThrottleTimer = null;
    }
    if (this.diagnosisSearchTimer) {
      clearTimeout(this.diagnosisSearchTimer);
      this.diagnosisSearchTimer = null;
    }
  },

  methods: {
    // 跳转到中药选择页面
    gotoMedicineSelect() {
      const storageKey = 'helper_selected_medicine';
      uni.removeStorageSync(storageKey);
      
      // 准备已选药品数据，包含煎煮方法索引
      const selectedMedicinesData = this.selectedMedicines.map(medicine => {
        // 找到煎煮方法在选项中的索引
        const decoctionIndex = this.getDecoctionIndex(medicine.decoction_method);
        return {
          ...medicine,
          decoctionIndex: decoctionIndex
        };
      });
      
      uni.navigateTo({
        url: `/pages/medicine/drugs-select?selected=${encodeURIComponent(JSON.stringify(selectedMedicinesData))}`,
        events: {
          medicineSelected: (medicines) => {
            // medicines 现在是一个数组，包含多个药品
            if (Array.isArray(medicines) && medicines.length > 0) {
              medicines.forEach(medicine => {
                // 检查中药是否已经选择过
                const existingIndex = this.selectedMedicines.findIndex(m => m.id === medicine.id);
                if (existingIndex === -1) {
                  // 为中药添加必要字段
                  const medicineWithDetails = {
                    ...medicine,
                    quantity: medicine.quantity || 0.5, // 数量
                    decoction_method: medicine.decoction_method || this.t('drugs_select.decoction_methods.none') // 煎煮方法
                  };
                  
                  // 添加新中药到中药列表
                  this.selectedMedicines.push(medicineWithDetails);
                } else {
                  // 如果中药已存在，更新其信息（包括煎煮方法）
                  this.selectedMedicines[existingIndex] = {
                    ...this.selectedMedicines[existingIndex],
                    quantity: medicine.quantity || this.selectedMedicines[existingIndex].quantity,
                    decoction_method: medicine.decoction_method || this.selectedMedicines[existingIndex].decoction_method
                  };
                }
              });
            }
            uni.removeStorageSync(storageKey);
          }
        }
      });
    },
    
    // 移除中药
    removeMedicine(index) {
      this.selectedMedicines.splice(index, 1);
    },
    
    // 获取煎煮方法索引
    getDecoctionIndex(decoction_method) {
      // 煎煮方法选项，需要与drugs-select.vue中的选项保持一致
      const decoctionOptions = [
        this.t('drugs_select.decoction_methods.none'),
        this.t('drugs_select.decoction_methods.after'),
        this.t('drugs_select.decoction_methods.before'),
        this.t('drugs_select.decoction_methods.wrap'),
        this.t('drugs_select.decoction_methods.melt'),
        this.t('drugs_select.decoction_methods.take')
      ];
      const index = decoctionOptions.findIndex(option => option === decoction_method);
      return index >= 0 ? index : 0; // 如果找不到，默认返回0
    },
    
    // 增加剂数
    increaseDosage() {
      this.dosageCount++;
    },
    
    // 减少剂数
    decreaseDosage() {
      if (this.dosageCount > 1) {
        this.dosageCount--;
      }
    },
    
    // 剂数输入框变化处理
    onDosageCountChange() {
      // 确保剂数至少为1
      if (this.dosageCount < 1) {
        this.dosageCount = 1;
      }
      // 转换为整数
      this.dosageCount = parseInt(this.dosageCount) || 1;
    },
    
    // 显示备注输入框
    showRemarksInput() {
      uni.showModal({
        title: this.t('prescription.remarks_title'),
        content: '',
        editable: true,
        placeholderText: this.t('prescription.remarks_placeholder_text'),
        success: (res) => {
          if (res.confirm && res.content) {
            this.formData.usage_notes = res.content;
          }
        }
      });
    },
    
    // 诊断搜索处理
    onDiagnosisSearch() {
      if (this.diagnosisSearchTimer) {
        clearTimeout(this.diagnosisSearchTimer);
      }
      
      this.diagnosisSearchTimer = setTimeout(() => {
        this.searchDiagnosis();
      }, 500);
    },
    
                   // 显示诊断弹窗
      openDiagnosisModal() {
        this.showDiagnosisModal = true;
        this.diagnosisSearch = '';
        this.diagnosisSearchResults = [];
        this.showDiagnosisSearchResults = false;
        // 重置分页状态
        this.currentPage = 1;
        this.hasMoreData = true;
        this.isRefreshing = false;
        this.showPullToRefresh = false;
        this.scrollThrottleTimer = null;
      },
      
                    // 关闭诊断弹窗
       closeDiagnosisModal() {
         // 清理定时器
         if (this.scrollThrottleTimer) {
           clearTimeout(this.scrollThrottleTimer);
           this.scrollThrottleTimer = null;
         }
         
         // 添加关闭动画
         const modal = document.querySelector('.diagnosis-modal');
         if (modal) {
           modal.classList.add('closing');
           setTimeout(() => {
             this.showDiagnosisModal = false;
             this.diagnosisSearch = '';
             this.diagnosisSearchResults = [];
             this.showDiagnosisSearchResults = false;
             // 重置翻页状态
             this.currentPage = 1;
             this.hasMoreData = true;
             this.isRefreshing = false;
             this.showPullToRefresh = false;
           }, 300);
         } else {
           this.showDiagnosisModal = false;
           this.diagnosisSearch = '';
           this.diagnosisSearchResults = [];
           this.showDiagnosisSearchResults = false;
                        // 重置翻页状态
             this.currentPage = 1;
             this.hasMoreData = true;
             this.isRefreshing = false;
             this.showPullToRefresh = false;
         }
       },
    
    // 清空诊断搜索
    clearDiagnosisSearch() {
      this.diagnosisSearch = '';
      this.diagnosisSearchResults = [];
      this.showDiagnosisSearchResults = false;
    },
    
         // 搜索诊断
     async searchDiagnosis(isLoadMore = false) {
       if (!this.diagnosisSearch.trim()) {
         this.diagnosisSearchResults = [];
         return;
       }
       
       if (isLoadMore) {
         this.isRefreshing = true;
       } else {
         this.diagnosisLoading = true;
         this.currentPage = 1;
         this.diagnosisSearchResults = [];
       }
       
       try {
         const res = await getDisease({
           pageSize: 10,
           page: this.currentPage,
           fjbname: this.diagnosisSearch.trim()
         });
         
         if (res.code === 200 && res.result) {
           const newItems = res.result.items || [];
           if (isLoadMore) {
             this.diagnosisSearchResults = [...this.diagnosisSearchResults, ...newItems];
           } else {
             this.diagnosisSearchResults = newItems;
           }
           
           // 判断是否还有更多数据
           this.hasMoreData = newItems.length === 10;
           
           // 显示下拉翻页提示（仅在首次搜索且有更多数据时）
           if (!isLoadMore && this.hasMoreData) {
             this.showPullToRefresh = true;
             setTimeout(() => {
               this.showPullToRefresh = false;
             }, 2000);
           }
         } else {
           if (!isLoadMore) {
             this.diagnosisSearchResults = [];
           }
           this.hasMoreData = false;
         }
       } catch (error) {
         console.error('搜索诊断失败:', error);
         if (!isLoadMore) {
           this.diagnosisSearchResults = [];
         }
         this.hasMoreData = false;
                } finally {
           this.diagnosisLoading = false;
           this.isRefreshing = false;
         }
     },
     
     // 处理弹窗滚动事件（已移除，改为按钮加载更多）
     
     // 加载更多诊断
     async loadMoreDiagnosis() {
       if (this.isRefreshing || !this.hasMoreData) return;
       
       try {
         this.currentPage++;
         await this.searchDiagnosis(true);
       } catch (error) {
         console.error('加载更多诊断失败:', error);
         // 如果加载失败，回退页码
         this.currentPage--;
         this.isRefreshing = false;
         
         // 显示错误提示
         uni.showToast({
           title: this.t('prescription.load_more_failed'),
           icon: 'none'
         });
       }
     },
    
      // 单选诊断（每次选择一个，支持多次打开弹窗添加多个）
      selectSingleDiagnosis(item) {
        // 检查是否已经选择了这个诊断
        const existingIndex = this.selectedDiagnoses.findIndex(diagnosis => diagnosis.id === item.id);
        
        if (existingIndex === -1) {
          // 如果诊断不存在，添加到列表中
          this.selectedDiagnoses.push(item);
          // 更新 formData.diagnosis，将所有诊断名称用逗号连接
          this.formData.diagnosis = this.selectedDiagnoses.map(d => d.fjbname).join('、');
          
          // 显示添加成功提示
          uni.showToast({
            title: '诊断添加成功',
            icon: 'success',
            duration: 1000
          });
          
          // 选择成功后关闭弹窗
          this.closeDiagnosisModal();
        } else {
          // 如果诊断已存在，显示提示
          uni.showToast({
            title: '该诊断已选择',
            icon: 'none'
          });
        }
      },

       // 移除诊断
       removeDiagnosis(index) {
         // 移除指定索引的诊断
         this.selectedDiagnoses.splice(index, 1);
         
         // 更新 formData.diagnosis
         if (this.selectedDiagnoses.length > 0) {
           this.formData.diagnosis = this.selectedDiagnoses.map(d => d.fjbname).join('、');
         } else {
           this.formData.diagnosis = '';
         }
       },
    
    
    // 添加点击外部区域监听器
    addClickOutsideListener() {
      // 在uni-app中，我们可以通过监听页面点击事件来实现
      // 这里使用一个简单的定时器来检查点击状态
      setTimeout(() => {
        // 隐藏搜索结果
        this.showDiagnosisSearchResults = false;
      }, 100);
    },
    
    // 加载用药医嘱相关数据
    async loadMedicationData() {
      try {
        // 获取用药时间选项
        const timeRes = await getDict({ code: 'zyyysj' });
        if (timeRes.code === 200 && timeRes.result) {
          this.medicationTimeOptions = timeRes.result;
        }
        
        // 获取用药禁忌选项
        const contraindicationsRes = await getDict({ code: 'yyjj' });
        if (contraindicationsRes.code === 200 && contraindicationsRes.result) {
          this.medicationContraindicationsOptions = contraindicationsRes.result;
        }
      } catch (error) {
        console.error('获取用药医嘱数据失败:', error);
      }
    },
    
    // 显示用药说明输入框
    showMedicationInstructionsInput() {
      uni.showModal({
        title: this.t('prescription.medication_instructions_title'),
        content: this.formData.medication_instructions || '',
        editable: true,
        placeholderText: this.t('prescription.medication_instructions_placeholder'),
        success: (res) => {
          if (res.confirm) {
            this.formData.medication_instructions = res.content || '';
          }
        }
      });
    },
    
    // 显示用药时间选择器
    showMedicationTimePicker() {
      if (this.medicationTimeOptions.length === 0) {
        uni.showToast({ title: this.t('prescription.no_medication_time_options'), icon: 'none' });
        return;
      }
      
      const options = this.medicationTimeOptions.map(item => item.label);
      
      uni.showActionSheet({
        itemList: options,
        success: (res) => {
          const selectedOption = this.medicationTimeOptions[res.tapIndex];
          this.formData.medication_time = selectedOption.label;
        }
      });
    },
    
    // 显示用药禁忌选择器
    showMedicationContraindicationsPicker() {
      if (this.medicationContraindicationsOptions.length === 0) {
        uni.showToast({ title: this.t('prescription.no_medication_contraindications_options'), icon: 'none' });
        return;
      }
      
      const options = this.medicationContraindicationsOptions.map(item => item.label);
      
      uni.showActionSheet({
        itemList: options,
        success: (res) => {
          const selectedOption = this.medicationContraindicationsOptions[res.tapIndex];
          this.formData.medication_contraindications = selectedOption.label;
        }
      });
    },
    
    // 提交处方
    async submitPrescription() {
       // 验证临床诊断（诊断和辨证至少填写一项）
       if (this.selectedDiagnoses.length === 0 && !this.formData.dialectic.trim()) {
         uni.showToast({ 
           title: this.t('prescription.diagnosis') + '或' + this.t('prescription.syndrome_differentiation') + '至少填写一项', 
           icon: 'none' 
         });
         return;
       }
       // 验证中药选择
      if (this.selectedMedicines.length === 0) {
        uni.showToast({ title: this.t('prescription.select_medicine_first'), icon: 'none' });
        return;
      }
      
      // 验证用法用量
      if (!this.formData.usage_days || this.formData.usage_days < 1) {
        uni.showToast({ title: this.t('prescription.usage_days_required'), icon: 'none' });
        return;
      }
      
      if (!this.formData.usage_doses || this.formData.usage_doses < 1) {
        uni.showToast({ title: this.t('prescription.usage_doses_required'), icon: 'none' });
        return;
      }
      
      if (!this.formData.usage_times || this.formData.usage_times < 1) {
        uni.showToast({ title: this.t('prescription.usage_times_required'), icon: 'none' });
        return;
      }
      
      if (!this.formData.usage_amount || this.formData.usage_amount < 1) {
        uni.showToast({ title: this.t('prescription.usage_amount_required'), icon: 'none' });
        return;
      }
      
      // 验证用药医嘱
      if (!this.formData.medication_instructions || this.formData.medication_instructions.trim() === '') {
        uni.showToast({ title: this.t('prescription.medication_instructions_required'), icon: 'none' });
        return;
      }
      
      if (!this.formData.medication_time || this.formData.medication_time.trim() === '') {
        uni.showToast({ title: this.t('prescription.medication_time_required'), icon: 'none' });
        return;
      }
      
             // 准备完整的处方数据
       const prescriptionData = {
         ...this.medicalRecordData,
         selected_medicines: this.selectedMedicines,
         selected_diagnoses: this.selectedDiagnoses, // 添加完整的诊断信息
         dosage_count: this.dosageCount,
         total_weight: this.totalDosageWeight,
         details: this.formData,
         doctor_id: this.userInfo.id,
         doctor_signature: this.userInfo.signature_path,
         signature_date: this.getCurrentDate()
       };
      
      // console.log('提交处方数据:', prescriptionData);
      
      // 这里可以调用API保存数据
      const res = await treatmentRecordChineseMedicine(prescriptionData);
      // console.log('提交处方数据:', res);
      
      uni.showToast({
        title: res.message, 
        icon: 'success' 
      });
      
             // 保存成功后跳转到首页
       setTimeout(() => {
         // 将完整的处方数据存储到本地，供其他页面使用
        //  uni.setStorageSync('medical_complete_prescription', prescriptionData);
        uni.removeStorageSync("medical_complete_prescription");
        uni.removeStorageSync("medical_complete_record");
        uni.removeStorageSync("medical_history_data");
        uni.removeStorageSync("medical_patient_info");
         // 跳转到首页（使用 switchTab 因为 my/index 是 tabbar 页面）
         uni.switchTab({
           url: '/pages/my/index'
         });
       }, 1000);
    },
    
    // 获取当前日期
    getCurrentDate() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    
    // 获取治疗师姓名
    getTherapistName() {
      try {
        if (this.userInfo && this.userInfo.first_name && this.userInfo.last_name) {
          return `${this.userInfo.last_name}${this.userInfo.first_name}`;
        } else if (this.userInfo && this.userInfo.username) {
          return this.userInfo.username;
        } else {
          return this.t('medical.not_filled');
        }
      } catch (error) {
        return this.t('medical.not_filled');
      }
    },
    
    // 治疗师重新签名
    gotoTherapistSign() {
      // 跳转签名页，签名完成后回传图片
      uni.navigateTo({
        url: '/pages/order/sign',
        events: {
          signImage: (img) => {
            this.updateTherapistSignature(img);
          }
        }
      });
    },
    
    // 更新治疗师签名
    async updateTherapistSignature(img) {
      try {
        const res = await resetSignature({ 
          signature: img, 
          user_id: this.userInfo && this.userInfo.id ? this.userInfo.id : null
        });
        if (res.code == 200) {
          // 更新治疗师签名
          this.therapistSignature = res.result.url;
          // 更新本地存储的用户信息
          if (this.userInfo) {
            this.userInfo.signature = res.result.url;
            this.userInfo.signature_path = res.result.save_path;
            this.userInfo.signFile = res.result.url;
            uni.setStorageSync('userInfo', this.userInfo);
          }
          uni.showToast({ 
            title: this.t('medical.signature_updated'), 
            icon: 'success' 
          });
        }
      } catch (error) {
        console.error('更新治疗师签名失败:', error);
        uni.showToast({ 
          title: this.t('common.update_failed'), 
          icon: 'error' 
        });
      }
    },
    
    // 加载治疗师签名
    loadTherapistSignature() {
      try {
        if (this.userInfo && this.userInfo.signature) {
          this.therapistSignature = this.userInfo.signature;
        }
      } catch (error) {
        console.log('加载治疗师签名失败:', error);
      }
    },
    
    // 弹窗滚动事件处理
    onModalScroll(e) {
      // 在uni-app中，滚动事件可能不会正确触发
      // 这里保留作为备用方案
      try {
        const { scrollTop, scrollHeight, clientHeight } = e.target;
        
        // 当滚动到底部时，自动加载更多数据
        if (scrollHeight - scrollTop - clientHeight < 50 && this.hasMoreData && !this.isRefreshing) {
          this.loadMoreDiagnosis();
        }
      } catch (error) {
        // 如果滚动事件处理失败，忽略错误
        console.log('滚动事件处理失败，使用触摸事件作为备用');
      }
    },
    
    // 触摸滚动处理（uni-app 兼容）
    onModalTouchMove(e) {
      // 使用节流来避免频繁触发
      if (this.scrollThrottleTimer) return;
      
      this.scrollThrottleTimer = setTimeout(() => {
        this.scrollThrottleTimer = null;
        this.checkScrollPosition();
      }, 200);
    },
    
    // 检查滚动位置
    checkScrollPosition() {
      if (!this.hasMoreData || this.isRefreshing) return;
      
      // 使用 uni.createSelectorQuery 获取滚动信息
      const query = uni.createSelectorQuery().in(this);
      query.select('.modal-results').boundingClientRect((rect) => {
        if (rect) {
          // 获取系统信息
          const systemInfo = uni.getSystemInfoSync();
          const windowHeight = systemInfo.windowHeight;
          
          // 检查是否滚动到底部（距离底部100px以内）
          const isNearBottom = rect.height + rect.top >= windowHeight - 100;
          
          if (isNearBottom) {
            console.log('检测到滚动到底部，自动加载更多数据');
            this.loadMoreDiagnosis();
          }
        }
      }).exec();
    },
  }
}
</script>

<style scoped>
.container {
  background: #fff;
  min-height: 100vh;
  padding-bottom: 140rpx;
  padding-top: calc(88rpx + var(--status-bar-height, 44rpx));
  padding-left: 4rpx;
  padding-right: 4rpx;
  overflow-x: hidden;
  box-sizing: border-box;
}

/* 自定义导航栏样式 */
.custom-navbar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 88rpx;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  padding-top: var(--status-bar-height, 44rpx);
}

.navbar-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  text-align: center;
}

/* 临床诊断区样式 */
.clinical-diagnosis-section {
  background: #fff;
  border-radius: 16rpx;
  padding: 16rpx;
  margin: 16rpx 8rpx;
  border: 1rpx solid #e9ecef;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  position: relative;
}

.clinical-diagnosis-section::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4rpx;
  background: linear-gradient(90deg, #007bff, #0056b3);
  border-radius: 16rpx 16rpx 0 0;
}

.clinical-diagnosis-section .section-header {
  margin-bottom: 24rpx;
  padding-bottom: 16rpx;
  border-bottom: 1rpx solid #e9ecef;
}

.clinical-diagnosis-section .section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  display: block;
}

.clinical-diagnosis-section .section-subtitle {
  font-size: 24rpx;
  color: #6c757d;
  margin-top: 8rpx;
  display: block;
}

.clinical-diagnosis-section .diagnosis-content {
  margin-top: 20rpx;
}

.clinical-diagnosis-section .diagnosis-row {
  display: flex;
  align-items: flex-start;
  gap: 12rpx;
  margin-bottom: 20rpx;
  padding-bottom: 16rpx;
  border-bottom: 1rpx solid #f8f9fa;
}

.clinical-diagnosis-section .diagnosis-row:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}

.clinical-diagnosis-section .diagnosis-label {
  font-size: 28rpx;
  font-weight: 600;
  color: #495057;
  min-width: 80rpx;
  text-align: left;
  padding-top: 8rpx;
  flex-shrink: 0;
}

.clinical-diagnosis-section .diagnosis-input-area {
  flex: 1;
  position: relative;
}

/* 诊断输入容器样式 */
.diagnosis-input-container {
  width: 100%;
}

.add-diagnosis-btn {
  background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
  color: #fff;
  border: none;
  border-radius: 16rpx;
  padding: 20rpx 24rpx;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  gap: 12rpx;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  width: 100%;
  justify-content: center;
  box-shadow: 0 4rpx 12rpx rgba(40, 167, 69, 0.3);
  position: relative;
  overflow: hidden;
}

.add-diagnosis-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s;
}

.add-diagnosis-btn:hover::before {
  left: 100%;
}

.add-diagnosis-btn:active {
  background: linear-gradient(135deg, #218838 0%, #1ea085 100%);
  transform: translateY(2rpx) scale(0.98);
  box-shadow: 0 2rpx 8rpx rgba(40, 167, 69, 0.4);
}

.add-icon {
  font-size: 32rpx;
  font-weight: bold;
}

.add-text {
  font-size: 28rpx;
  font-weight: 500;
}

/* 辨证输入框样式 */
.syndrome-input {
  width: 100%;
  height: 72rpx;
  padding: 0 20rpx;
  border: 2rpx solid #e9ecef;
  border-radius: 12rpx;
  font-size: 28rpx;
  background: #fff;
  transition: all 0.3s ease;
  box-sizing: border-box;
}

.syndrome-input:focus {
  border-color: #007bff;
  box-shadow: 0 0 0 3rpx rgba(0, 123, 255, 0.1);
  outline: none;
}

/* 搜索结果样式 */
.search-results {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: #fff;
  border: 1rpx solid #e9ecef;
  border-radius: 12rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
  z-index: 1000;
  max-height: 400rpx;
  overflow-y: auto;
  margin-top: 4rpx;
}

.search-loading, .search-no-results {
  padding: 24rpx;
  text-align: center;
  color: #6c757d;
  font-size: 26rpx;
}

.search-result-list {
  width: 100%;
}

.search-result-item {
  padding: 20rpx 24rpx;
  border-bottom: 1rpx solid #f8f9fa;
  cursor: pointer;
  transition: background-color 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: space-between;
  min-height: 80rpx;
}

.search-result-item:last-child {
  border-bottom: none;
}

.search-result-item:hover {
  background-color: #f8f9fa;
}

.search-result-item:active {
  background-color: #e9ecef;
}

.result-content {
  flex: 1;
}

.result-name {
  display: block;
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 8rpx;
}

.result-code {
  display: block;
  font-size: 24rpx;
  color: #6c757d;
}

.selection-indicator {
  margin-left: 16rpx;
  flex-shrink: 0;
}

.unselected-icon {
  color: #6c757d;
  font-size: 32rpx;
}

/* 诊断显示样式 */
.diagnosis-display {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
  width: 100%;
}

.diagnosis-list {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
  width: 100%;
}

.diagnosis-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  padding: 16rpx 20rpx;
  border-radius: 16rpx;
  border: 2rpx solid #e9ecef;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

.diagnosis-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 6rpx;
  height: 100%;
  background: linear-gradient(180deg, #66ea78 0%, #4ba268 100%);
  border-radius: 0 3rpx 3rpx 0;
}

.diagnosis-item:hover {
  transform: translateY(-2rpx);
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
  border-color: #66ea71;
}

.diagnosis-text {
  flex: 1;
  font-size: 28rpx;
  color: #2c3e50;
  word-break: break-all;
  line-height: 1.5;
  font-weight: 500;
  margin-left: 8rpx;
  padding-right: 12rpx;
}

.remove-diagnosis-btn {
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
  color: #fff;
  border: none;
  border-radius: 50%;
  width: 36rpx;
  height: 36rpx;
  font-size: 22rpx;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  margin-left: 12rpx;
  flex-shrink: 0;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 2rpx 8rpx rgba(255, 107, 107, 0.3);
  position: relative;
  overflow: hidden;
}

.remove-diagnosis-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s;
}

.remove-diagnosis-btn:hover::before {
  left: 100%;
}

.remove-diagnosis-btn:active {
  background: linear-gradient(135deg, #e5554a 0%, #d44a42 100%);
  transform: translateY(1rpx) scale(0.95);
  box-shadow: 0 1rpx 4rpx rgba(255, 107, 107, 0.4);
}

.edit-diagnosis-container {
  display: flex;
  justify-content: flex-start;
  margin-top: 16rpx;
  width: 100%;
}

.edit-diagnosis-btn {
  background: #fff;
  color: #28a745;
  border: 2rpx solid #28a745;
  border-radius: 20rpx;
  padding: 5rpx 50rpx;
  font-size: 26rpx;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  white-space: nowrap;
  box-shadow: 0 2rpx 8rpx rgba(40, 167, 69, 0.1);
  position: relative;
  overflow: hidden;
  align-self: flex-start;
  margin-left: 0;
  margin-right: auto;
}

.edit-diagnosis-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(40, 167, 69, 0.1), transparent);
  transition: left 0.5s;
}

.edit-diagnosis-btn:hover::before {
  left: 100%;
}

.edit-diagnosis-btn:active {
  background: #f0f8f0;
  color: #218838;
  border-color: #218838;
  transform: translateY(2rpx) scale(0.98);
  box-shadow: 0 1rpx 4rpx rgba(40, 167, 69, 0.2);
}

/* 中药选择区样式 */
.medicine-selection-section {
  background: #f0f8f0;
  border-radius: 16rpx;
  padding: 16rpx;
  margin: 16rpx 8rpx;
  border: 2rpx solid #d4edda;
  position: relative;
}

.medicine-selection-section::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 6rpx;
  background: linear-gradient(90deg, #28a745, #5cb85c);
  border-radius: 16rpx 16rpx 0 0;
}

.section-header {
  margin-bottom: 16rpx;
  padding-bottom: 12rpx;
  border-bottom: 2rpx solid #d4edda;
}

.section-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #28a745;
  display: block;
}

.medicine-btn {
  background: #28a745 !important;
  color: #fff !important;
  border: 2rpx solid #28a745 !important;
  transition: all 0.3s ease;
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 28rpx;
  border-radius: 8rpx;
}

.medicine-btn:active {
  background: #218838 !important;
  transform: scale(0.98);
}

/* 已选中药列表样式 */
.selected-medicines-list {
  width: 100%;
  margin-top: 12rpx;
  margin-bottom: 12rpx;
}

.selected-medicine-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fff;
  border-radius: 12rpx;
  padding: 16rpx;
  margin-bottom: 12rpx;
  border: 1rpx solid #d4edda;
  box-shadow: 0 2rpx 8rpx rgba(40, 167, 69, 0.1);
}

.medicine-info-group {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-shrink: 0;
}

.medicine-info {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.medicine-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.medicine-meta {
  display: flex;
  gap: 8px;
  font-size: 14px;
  color: #666;
}

.medicine-quantity {
  color: #28a745;
  font-weight: bold;
}

.medicine-method {
  color: #28a745;
  font-weight: bold;
}

.remove-medicine-btn {
  background: #dc3545;
  color: #fff;
  border-radius: 6rpx;
  padding: 5rpx 10rpx;
  font-size: 24rpx;
  border: none;
  white-space: nowrap;
  margin-left: 16rpx;
}

/* 药量计算器样式 */
.dosage-calculator {
  background: #fff;
  border-radius: 12rpx;
  padding: 16rpx;
  margin-top: 12rpx;
  border: 2rpx solid #28a745;
  box-shadow: 0 2rpx 8rpx rgba(40, 167, 69, 0.15);
}

.calculator-header {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
  padding-bottom: 12rpx;
  border-bottom: 1rpx solid #e9ecef;
}

.calculator-icon {
  font-size: 24rpx;
  margin-right: 8rpx;
}

.calculator-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #28a745;
}

.calculator-content {
  display: flex;
  justify-content: center;
}

.dosage-info {
  display: flex;
  align-items: center;
  gap: 8rpx;
  flex-wrap: wrap;
  justify-content: center;
}

.dosage-text {
  font-size: 26rpx;
  color: #28a745;
  font-weight: bold;
  background: #f0f8f0;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  border: 1rpx solid #d4edda;
}

.dosage-label {
  font-size: 24rpx;
  color: #666;
}

.quantity-selector {
  display: flex;
  align-items: center;
  border: 2rpx solid #28a745;
  border-radius: 24rpx;
  overflow: hidden;
  background: #fff;
}

.quantity-btn {
  width: 60rpx;
  height: 60rpx;
  background: #28a745;
  color: #fff;
  border: none;
  font-size: 28rpx;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s ease;
}

.quantity-btn:active {
  background: #218838;
  transform: scale(0.95);
}

.quantity-btn:disabled {
  background: #ccc;
  color: #999;
  cursor: not-allowed;
}

.quantity-btn.minus {
  border-radius: 24rpx 0 0 24rpx;
}

.quantity-btn.plus {
  border-radius: 0 24rpx 24rpx 0;
}

.quantity-input {
  width: 80rpx;
  height: 60rpx;
  border: none;
  text-align: center;
  font-size: 26rpx;
  font-weight: bold;
  color: #28a745;
  background: #fff;
  outline: none;
}

.total-dosage {
  font-size: 26rpx;
  color: #28a745;
  font-weight: bold;
  background: #fff;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  border: 1rpx solid #28a745;
}

/* 用法用量样式 */
.usage-dosage-section {
  background: #fff;
  border-radius: 12rpx;
  padding: 16rpx;
  margin-top: 12rpx;
  border: 2rpx solid #28a745;
  box-shadow: 0 2rpx 8rpx rgba(40, 167, 69, 0.15);
}

.usage-content {
  margin-top: 16rpx;
}

.usage-row {
  display: flex;
  align-items: center;
  gap: 6rpx;
  flex-wrap: wrap;
  justify-content: center;
}

.required-mark {
  color: #e74c3c;
  font-size: 24rpx;
  font-weight: bold;
}

.usage-input {
  width: 60rpx;
  height: 50rpx;
  border: 2rpx solid #28a745;
  border-radius: 8rpx;
  text-align: center;
  font-size: 24rpx;
  font-weight: bold;
  color: #28a745;
  background: #fff;
  outline: none;
}

.usage-input.amount-input {
  width: 80rpx;
}

.usage-unit {
  font-size: 24rpx;
  color: #333;
  font-weight: 500;
}

.usage-text {
  font-size: 24rpx;
  color: #666;
}

/* 备注信息样式 */
.remarks-content {
  margin-top: 24rpx;
  padding-top: 20rpx;
  border-top: 1rpx solid #d4edda;
}

.remarks-header {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
  padding-bottom: 12rpx;
  border-bottom: 1rpx solid #d4edda;
}

.remarks-icon {
  font-size: 24rpx;
  margin-right: 8rpx;
}

.remarks-title {
  font-size: 26rpx;
  font-weight: bold;
  color: #28a745;
}

.remarks-input-area {
  text-align: center;
}

.remarks-placeholder {
  font-size: 26rpx;
  color: #28a745;
  cursor: pointer;
  padding: 12rpx 24rpx;
  background: #f0f8f0;
  border-radius: 20rpx;
  border: 1rpx solid #d4edda;
  transition: all 0.3s ease;
}

.remarks-placeholder:active {
  background: #d4edda;
  transform: scale(0.98);
}

.remarks-display {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16rpx;
}

.remarks-text {
  font-size: 26rpx;
  color: #333;
  background: #f0f8f0;
  padding: 12rpx 24rpx;
  border-radius: 20rpx;
  border: 1rpx solid #d4edda;
  max-width: 400rpx;
  word-break: break-all;
}

.edit-remarks-btn {
  background: #28a745;
  color: #fff;
  border: none;
  border-radius: 20rpx;
  padding: 8rpx 16rpx;
  font-size: 22rpx;
  cursor: pointer;
  transition: all 0.3s ease;
}

.edit-remarks-btn:active {
  background: #218838;
  transform: scale(0.98);
}

/* 用药医嘱样式 */
.medication-instructions-section {
  background: #fff;
  border-radius: 12rpx;
  padding: 16rpx;
  margin-top: 12rpx;
  border: 2rpx solid #28a745;
  box-shadow: 0 2rpx 8rpx rgba(40, 167, 69, 0.15);
}

.medication-content {
  margin-top: 16rpx;
}

.medication-row {
  display: flex;
  align-items: center;
  padding: 16rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  position: relative;
}

.medication-row:last-child {
  border-bottom: none;
}

.medication-label {
  margin-right: 8rpx;
}

.medication-text {
  font-size: 26rpx;
  color: #333;
  font-weight: 500;
  min-width: 100rpx;
}

.medication-input-area {
  flex: 1;
  margin: 0 12rpx;
  cursor: pointer;
}

.medication-placeholder {
  font-size: 26rpx;
  color: #28a745;
  padding: 12rpx 16rpx;
  background: #f0f8f0;
  border-radius: 8rpx;
  border: 1rpx solid #d4edda;
  display: block;
  text-align: center;
}

.medication-display {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16rpx;
}

.medication-value {
  font-size: 26rpx;
  color: #333;
  background: #f0f8f0;
  padding: 12rpx 16rpx;
  border-radius: 8rpx;
  border: 1rpx solid #d4edda;
  flex: 1;
  word-break: break-all;
}

.edit-medication-btn {
  background: #28a745;
  color: #fff;
  border: none;
  border-radius: 20rpx;
  padding: 8rpx 16rpx;
  font-size: 22rpx;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.edit-medication-btn:active {
  background: #218838;
  transform: scale(0.98);
}

.medication-arrow {
  font-size: 24rpx;
  color: #999;
  margin-left: 8rpx;
}

.fixed-bottom-btn {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  padding: 16rpx 24rpx 32rpx 24rpx;
  z-index: 100;
  box-shadow: 0 -2rpx 8rpx #eee;
}

.fill-btn {
  width: 100%;
  background: #1976d2;
  color: #fff;
  border-radius: 8rpx;
  font-size: 30rpx;
  height: 80rpx;
  line-height: 80rpx;
  display: block;
}

/* 诊断弹窗样式 */
.diagnosis-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 2000;
  display: flex;
  align-items: flex-end;
  justify-content: center;
  padding: 0;
}

.diagnosis-modal {
  background: #fff;
  border-radius: 16rpx 16rpx 0 0;
  width: 100%;
  max-width: 680rpx;
  height: 80vh;
  overflow: hidden;
  box-shadow: 0 -8rpx 32rpx rgba(0, 0, 0, 0.3);
  animation: slideUp 0.3s ease-out;
  display: flex;
  flex-direction: column;
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12rpx 20rpx;
  border-bottom: 1rpx solid #e9ecef;
  background: #f8f9fa;
  flex-shrink: 0;
}

.modal-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 40rpx;
  color: #6c757d;
  cursor: pointer;
  padding: 8rpx;
  border-radius: 50%;
  transition: all 0.3s ease;
}

.close-btn:active {
  background: #e9ecef;
  color: #333;
}

.modal-search {
  position: relative;
  padding: 12rpx 20rpx;
  border-bottom: 1rpx solid #e9ecef;
  flex-shrink: 0;
}

.modal-search-input {
  width: 100%;
  height: 72rpx;
  padding: 0 20rpx;
  border: 2rpx solid #e9ecef;
  border-radius: 12rpx;
  font-size: 28rpx;
  background: #fff;
  transition: all 0.3s ease;
  box-sizing: border-box;
}

.modal-search-input:focus {
  border-color: #007bff;
  box-shadow: 0 0 0 3rpx rgba(0, 123, 255, 0.1);
  outline: none;
}

.clear-search-btn {
  position: absolute;
  right: 40rpx;
  top: 50%;
  transform: translateY(-50%);
  background: #6c757d;
  color: #fff;
  border: none;
  border-radius: 50%;
  width: 40rpx;
  height: 40rpx;
  font-size: 24rpx;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.clear-search-btn:active {
  background: #495057;
}

.modal-results {
  flex: 1;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  min-height: 0;
  padding: 8rpx 0;
  height: calc(80vh - 200rpx);
}

/* 下拉翻页指示器样式 */
.pull-to-refresh {
  padding: 16rpx 24rpx;
  text-align: center;
  color: #6c757d;
  font-size: 24rpx;
  background: #f8f9fa;
  border-top: 1rpx solid #e9ecef;
}

/* 弹窗动画 */
@keyframes slideUp {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}

@keyframes slideDown {
  from {
    transform: translateY(0);
  }
  to {
    transform: translateY(100%);
  }
}

.diagnosis-modal.closing {
  animation: slideDown 0.3s ease-in;
}

.search-placeholder {
  padding: 48rpx 24rpx;
  text-align: center;
  color: #6c757d;
  font-size: 26rpx;
}

.search-results-count {
  padding: 16rpx 24rpx;
  text-align: center;
  color: #28a745;
  font-size: 24rpx;
  background: #f0f8f0;
  border-bottom: 1rpx solid #d4edda;
  font-weight: 500;
}



/* 加载中提示样式 */
.loading-more {
  padding: 16rpx 24rpx;
  text-align: center;
  color: #6c757d;
  font-size: 24rpx;
  background: #f8f9fa;
  border-top: 1rpx solid #e9ecef;
}

/* 没有更多数据提示样式 */
.no-more-data {
  padding: 16rpx 24rpx;
  text-align: center;
  color: #6c757d;
  font-size: 24rpx;
  background: #f8f9fa;
  border-top: 1rpx solid #e9ecef;
}

/* 理疗师信息样式 */
.therapist-info-section {
  background: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  margin: 16rpx 8rpx;
  border: 1rpx solid #e9ecef;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  position: relative;
}

.therapist-info-section::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4rpx;
  background: linear-gradient(90deg, #6f42c1, #5a32a3);
  border-radius: 16rpx 16rpx 0 0;
}

.therapist-info-section .section-header {
  margin-bottom: 24rpx;
  padding-bottom: 16rpx;
  border-bottom: 1rpx solid #e9ecef;
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.therapist-info-section .section-icon {
  font-size: 32rpx;
}

.therapist-info-section .section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #6f42c1;
}

.therapist-content {
  margin-top: 20rpx;
}

.therapist-row {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
  padding: 16rpx 0;
  border-bottom: 1rpx solid #f8f9fa;
  transition: all 0.3s ease;
}

.therapist-row:last-child {
  margin-bottom: 0;
  border-bottom: none;
}

.therapist-row:hover {
  background-color: #f8f9fa;
  border-radius: 8rpx;
  padding: 16rpx 12rpx;
  margin: 0 -12rpx 20rpx -12rpx;
}

.therapist-label {
  font-size: 28rpx;
  color: #495057;
  font-weight: 600;
  min-width: 160rpx;
  margin-right: 24rpx;
  flex-shrink: 0;
}

.therapist-value {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  flex: 1;
}

.therapist-signature-display {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.therapist-signature-image {
  width: 120rpx;
  height: 60rpx;
  border: 2rpx solid #e9ecef;
  border-radius: 8rpx;
  background: #fff;
  box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.therapist-signature-image:hover {
  border-color: #6f42c1;
  box-shadow: 0 4rpx 8rpx rgba(111, 66, 193, 0.2);
}

.no-signature {
  font-size: 24rpx;
  color: #6c757d;
  font-style: italic;
  padding: 8rpx 12rpx;
  background: #f8f9fa;
  border-radius: 6rpx;
  border: 1rpx dashed #dee2e6;
}

.therapist-sign-btn {
  background: linear-gradient(135deg, #6f42c1 0%, #5a32a3 100%);
  color: #fff;
  border: none;
  border-radius: 8rpx;
  font-size: 24rpx;
  padding: 8rpx 16rpx;
  margin-left: 16rpx;
  height: 48rpx;
  line-height: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
  white-space: nowrap;
  flex-shrink: 0;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 2rpx 8rpx rgba(111, 66, 193, 0.3);
  position: relative;
  overflow: hidden;
}

.therapist-sign-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s;
}

.therapist-sign-btn:hover::before {
  left: 100%;
}

.therapist-sign-btn:active {
  background: linear-gradient(135deg, #5a32a3 0%, #4a2a8a 100%);
  transform: translateY(2rpx) scale(0.98);
  box-shadow: 0 1rpx 4rpx rgba(111, 66, 193, 0.4);
}




</style>
